import Router from '@koa/router';
import db from '../mysqlHelper.js';
import logger from '../logger.js';
import response from '../response.js';
import moment from 'moment';
import fs from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log(__dirname);

const router = new Router();
router.prefix('/api');

router.post('/upload', async (ctx) => {
    try {
        let file = ctx.request.files.file;
        if (!file) {
            ctx.body = response.error('No file uploaded');
            return;
        }

        let reader = fs.createReadStream(file.filepath);
        let dirPath = join(__dirname, '../View/upload/');
        let filePath = '';
        let filename = ctx.request.body.filename;
        if (filename == undefined) {
            filename = file.originalFilename;
        }
        filePath = join(dirPath, filename);

        // 检查并创建目录
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true });
        }

        let upStream = fs.createWriteStream(filePath);

        reader.pipe(upStream);

        ctx.body = response.success({ url: `/upload/${filename}` });
    } catch (err) {
        console.log('file upload failed', err.message);
        ctx.body = response.fail('File upload failed');
    }
});

router.post('/:table/insert', async (ctx) => {
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let isExist = false;
    switch (ctx.params.table) {
        case 'enterprise':
            if (body.name == null) {
                ctx.body = response.fail('缺少必填字段 企业名称');
                return;
            }
            if (body.credit_code == null) {
                ctx.body = response.fail('缺少必填字段 统一信用代码');
                return;
            }
            isExist = await db.checkExist('enterprise', { name: body.name });
            if (isExist) {
                ctx.body = response.fail('相同的企业已经存在');
                return;
            }
            break;
        case 'vehicle':
            if (body.plate == null) {
                ctx.body = response.fail('缺少必填字段 车牌号码');
                return;
            }
            isExist = await db.checkExist('vehicle', { plate: body.plate });
            if (isExist) {
                ctx.body = response.fail('相同的车辆已经存在');
                return;
            }
            break;
        case 'transport_record':
            if (body.area_code == null) {
                ctx.body = response.fail('缺少必填字段 area_code');
                return;
            }
            let lastval = 1;
            //查询当前区域代码是对应的最后一次流水号
            let last = await db.findOne('current_no', { area_code: body.area_code });
            if (last == null) {
                await db.create('current_no', { area_code: body.area_code, last_value: 1 });
            } else {
                lastval = last.last_value + 1;
                await db.update('current_no', { last_value: lastval }, { area_code: body.area_code });
            }
            body.no = body.area_code + lastval.toString().padStart(6, '0');
            delete body.area_code;

            if ( body.status) {
                if (body.status ==2) //运单状态改变为待签收
                {
                    let sqls = [];
                    let plates = body.plate.split(',');
                    for (let plate of plates) {
                        let enable_vehicle = {
                            no: body.no,
                            plate: plate,
                            receive_credit_code: body.receive_credit_code,
                            start_time: moment().format('YYYY-MM-DD HH:mm:ss'),
                            end_time: moment().add(2, 'days').format('YYYY-MM-DD HH:mm:ss'),
                        }
                        sqls.push({ sql: 'insert into enable_vehicle set ?', params: enable_vehicle });
                    }
                    if (sqls.length > 0) {
                        res = await db.transaction(sqls);
                        if (res instanceof Error) {
                            logger.error(`${ctx.params.table} update error :` + res.message);
                            ctx.body = response.fail(`${ctx.params.table} update error :` + res.message);
                            return;
                        }
                    }


                }
            }


            break;
        default:
            break;
    }
    let res = await db.create(ctx.params.table, body);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} create error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} create error :` + res.message);
        return;
    }
    if (ctx.params.table == 'transport_record') {
        ctx.body = response.success({ no: body.no });
    } else {
        ctx.body = response.success({ id: res.insertId });
    }

});
function getConditions(tbaleName, body) {
    let conditions = {};
    //根据不同的表获取表的主键用于后续的更新和删除
    switch (tbaleName) {
        case 'enterprise':
            if (body.name == null) {
                return { code: 0, conditions, msg: '缺少必填字段 name' };
            }
            conditions = { name: body.name };
            return { code: 1, conditions: conditions };
        case 'vehicle':
            if (body.id == null) {
                return { code: 0, conditions, msg: '缺少必填字段 id' };
            }
            conditions = { id: body.id };
            return { code: 1, conditions: conditions };
        case 'transport_record':
            if (body.no == null) {
                return { code: 0, conditions, msg: '缺少必填字段 no' };
            }
            conditions = { no: body.no };
            return { code: 1, conditions: conditions };
        case 'configuration':
            if (body.config_no == null) {
                return { code: 0, conditions, msg: '缺少必填字段 config_no' };
            }
            conditions = { config_no: body.config_no };
            return { code: 1, conditions: conditions };
        default:
            if (body.keys != null) {
                //遍历keys的值，如果有值则添加到条件中
                for (let key of body.keys) {
                    if (body[key] != null) {
                        conditions[key] = body[key];
                    }
                }
                return { code: 1, conditions: conditions };
            }
            else if (body.id == null) {
                return { code: 0, conditions, msg: '缺少必填字段 id' };
            }
            conditions = { id: body.id };
            return { code: 1, conditions: conditions };
    }
}

router.post('/:table/update', async (ctx) => {
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions;
    let obj = await db.findOne(ctx.params.table, conditions);
    if (obj == null) {
        ctx.body = response.fail('要修改数据不存在');
        return;
    }
    if (ctx.params.table == 'transport_vehicle' && body.status) {
        if (body.status == 2) //运单状态改变为待签收
        {
            let sqls = [];
            let plates = obj.plate.split(',');
            if (body.plate != null) { plates = body.plate.split(','); }
            if (plates.length > 0) {
                //删除原有的允许通行的车辆
                sqls.push({ sql: `delete from enable_vehicle where no='${obj.no}'` });
            }
            for (let plate of plates) {
                let enable_vehicle = {
                    no: body.no,
                    plate: plate,
                    receive_credit_code: obj.receive_credit_code,
                    start_time: moment().format('YYYY-MM-DD HH:mm:ss'),
                    end_time: moment().add(2, 'days').format('YYYY-MM-DD HH:mm:ss'),
                }
                sqls.push({ sql: 'insert into enable_vehicle set ?', params: enable_vehicle });

            }
            if (sqls.length > 0) {
                res = await db.transaction(sqls);
                if (res instanceof Error) {
                    logger.error(`${ctx.params.table} update error :` + res.message);
                    ctx.body = response.fail(`${ctx.params.table} update error :` + res.message);
                    return;
                }
            }


        }
    }
    for (let key in body) {
        if (body[key] != undefined && body[key] != null) {
            obj[key] = body[key];
        }
    }
    res = await db.update(ctx.params.table, obj, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} update error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} update error :` + res.message);
        return;
    }





    ctx.body = response.success();
});

router.post('/:table/remove', async (ctx) => {
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions;
    res = await db.deleteRow(ctx.params.table, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} delete error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} delete error :` + res.message);
        return;
    }
    if (ctx.params.table == 'device') {
        memDB.deleteDevice({ sn: body.sn });
    }
    ctx.body = response.success();
});
router.post('/:table/getList', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        body = { limit: 10, offset: 0, direction: 'desc' };
    } else {
        if (!body.direction) body.direction = 'desc';
    }
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    let res = await db.findAll(ctx.params.table, body.conditions, body.orderBy, body.direction, body.limit, body.offset, body.areaArr,
        body.likeArr, body.leftJoinArr, body.inArr, body.dispColumn, body.customizeWhere);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} getList error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} getList error :` + res.message);
        return;
    }
    if (res.count) {
        ctx.body = response.success({ rows: res.rows, count: res.count });
        return;
    } else {
        ctx.body = response.success(res);
    }
});


export { router };
